package com.lizk.study.netty.day009;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Scattering与Gathering，读写取一个byteBuffer数组
 * @author lizhikui
 * @date 2019/6/26 0:43
 */
public class NioTest10 {

    public static void test(){
        List<String> names = Arrays.asList("XML", "Java", "HTML", "CSS");
        System.out.println(names);
//        System.out.println(names.stream().sorted(Collections.reverse();).collect(Collectors.toList()));
        Collections.reverse(names);
        System.out.println(names);
    }
    public static void main(String[] args) throws IOException {
        test();
        ByteBuffer buffer1 = ByteBuffer.allocate(10);
        ByteBuffer buffer2 = ByteBuffer.allocate(10);

        File file = FileUtil.createFile("NioTest10.txt");

        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel outChannel = outputStream.getChannel();
        outChannel.write(ByteBuffer.wrap("12345678900987654321".getBytes()));

        FileInputStream inputStream = new FileInputStream(file);
        FileChannel channel = inputStream.getChannel();

        ByteBuffer[] buffers = new ByteBuffer[]{buffer1,buffer2};

        channel.read(buffers);

        Arrays.stream(buffers)
                .peek(ByteBuffer::flip)
                .forEach(buffer->{
                    while (buffer.hasRemaining()) {
                        byte [] b = new byte[100];
                        buffer.get(b,0,buffer.remaining());
                        System.out.println(new String(b));
                    }
                });

        Arrays.stream(buffers)
                .peek(ByteBuffer::flip);

        ByteBuffer[] newBuffers = new ByteBuffer[2];
        newBuffers[0] =buffers[1];
        newBuffers[1] =buffers[0];

        outChannel.write(newBuffers);
        outChannel.close();
        channel.close();
    }
}
